package com.lgmshare.k3.receiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2018/3/27 16:58
 */
public class NotifyReceiver extends BroadcastReceiver {

    /**
     * 灰色保活手段唤醒广播的action
     */
    public final static String ACTION_WAKE_NOTIFY = "com.wake.gray";

    @Override
    public void onReceive(Context context, Intent intent) {
        //应用进程保活
        context = context.getApplicationContext();
        //Read last login state.

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceList = activityManager.getRunningServices(200);

        List<Class> serviceList = new ArrayList<>();
//        serviceList.add(LocationService.class);

        for (Class service : serviceList) {
            if (!isServiceRunning(runningServiceList, service.getName())) {
                context.startService(new Intent(context, service));
            }
        }
        //Since case of service is running but not tracking.
    }

    private static boolean isServiceRunning(List<ActivityManager.RunningServiceInfo> serviceList, String serviceName) {
        int size = serviceList == null ? 0 : serviceList.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                if (serviceList.get(i).service.getClassName().equals(serviceName)) {
                    return true;
                }
            }
        }
        return false;
    }
}
